package com.jinke.uang.ui.activity.personal;

import android.graphics.drawable.Drawable;
import android.os.CountDownTimer;
import android.text.SpannableString;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.view.View;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.jinke.uang.R;
import com.jinke.uang.base.BaseNormalActivity;
import com.jinke.uang.base.BaseResponse;
import com.jinke.uang.common.RouterMap;
import com.jinke.uang.constant.Constant;
import com.jinke.uang.constant.HttpConstant;
import com.jinke.uang.model.LoginModule;
import com.jinke.uang.presenter.CommonPresenter;
import com.jinke.uang.http.Urls;
import com.jinke.uang.utils.StringUtils;
import com.jinke.uang.utils.ToastUtils;
import com.jinke.uang.ui.webview.WebViewActivity;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnCheckedChanged;
import butterknife.OnClick;

/**
 * 注册界面
 */
@Route(path = RouterMap.REGISTER_PAGE)
public class RegisterActivity extends BaseNormalActivity<CommonPresenter,LoginModule>{

    @BindView(R.id.root_container_view)
    LinearLayout root_container_view;
    @BindView(R.id.et_userName)
    EditText etUserName;
    @BindView(R.id.et_verify)
    EditText etVerify;
    @BindView(R.id.et_password)
    EditText etPassword;
    @BindView(R.id.do_acquire_voice_code)
    TextView do_acquire_voice_code;
    @BindView(R.id.do_acquire_verify_code)
    TextView do_acquire_verify_code;
    @BindView(R.id.check_agreement)
    CheckBox checkAgreement;

    private boolean isStartCountDown = false;
    private CustomerCountDownTimer countDownTimer;

    private String mPhoneNum;

    @Override
    protected void initViews() {
        ButterKnife.bind(this);
    }

    @Override
    protected void onUIReady() {}

    @Override
    protected int getContentResId() {
        return R.layout.activity_register;
    }

    @Override
    protected CommonPresenter getPresenter() {
        return new CommonPresenter();
    }

    @Override
    protected LoginModule getModule() {
        return new LoginModule();
    }

    @Override
    public String getPageTitle() {
        return null;
    }

    @OnCheckedChanged(R.id.cb_show_psw)
    public void showPsw(CompoundButton compoundButton, boolean checked) {
        if (checked) {
            etPassword.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
        } else {
            etPassword.setTransformationMethod(PasswordTransformationMethod.getInstance());
        }
    }

    @OnClick({R.id.do_acquire_voice_code, R.id.do_acquire_verify_code, R.id
            .tv_check_agreement_text, R.id.register_btn, R.id.register_to_login, R.id
            .root_container_view})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.do_acquire_voice_code:
                if (!isStartCountDown) {
                    getVoiceCode();
                }
                break;
            case R.id.do_acquire_verify_code:
                if (!isStartCountDown) {
                    getVerifyCode();
                }
                break;
            case R.id.tv_check_agreement_text:
                ARouter.getInstance().build(RouterMap.WEB_VIEW_PAGE).withString(WebViewActivity
                        .PARAMS_URL, Urls.REGISTER_AGREEMENT_URL).navigation();
                break;
            case R.id.register_btn:
                mPhoneNum = etUserName.getText().toString();
                String psw = etPassword.getText().toString();
                String verifyCode = etVerify.getText().toString();
                String msg = verifyParams(mPhoneNum, psw, verifyCode);

                if (StringUtils.isEmpty(msg)) {
                    showLoadingView();
                    mPresenter.getData(HttpConstant.REGISTER_QUEST,null, mPhoneNum, psw, verifyCode, "1");
                } else {
                    ToastUtils.showShort(this, msg);
                }
                break;
            case R.id.register_to_login:
                finish();
                break;
            case R.id.root_container_view:
                hideSoftPan(root_container_view);
                break;
            default:
                break;
        }
    }

    private void getVerifyCode() {
        String phoneNum = etUserName.getText().toString();
        if (StringUtils.isEmpty(phoneNum)) {
            ToastUtils.showShort(RegisterActivity.this, getStringResource(R.string
                    .register_user_name_is_null));
            return;
        }
        showLoadingView();
        mPresenter.getData(HttpConstant.SMS_CODE,null,phoneNum);
    }

    private void getVoiceCode() {
        String phoneNum = etUserName.getText().toString();
        if (StringUtils.isEmpty(mPhoneNum)) {
            ToastUtils.showShort(RegisterActivity.this, getStringResource(R.string
                    .register_user_name_is_null));
            return;
        }
        showLoadingView();
        mPresenter.getData(HttpConstant.VOICE_CODE,null,phoneNum);
    }

    /**
     * 处理倒计时view
     */
    private void processCountDownView(final TextView countDownView, final SpannableString
            stringSpan) {
        isStartCountDown = true;
        if (countDownTimer == null) {
            countDownTimer = new CustomerCountDownTimer(59 * 1000, 1000);
        } else {
            countDownTimer.cancel();
        }
        countDownTimer.updateTextView(countDownView, stringSpan);
        do_acquire_voice_code.setEnabled(false);
        do_acquire_verify_code.setEnabled(false);

        countDownTimer.start();
    }

    //返回值
    @Override
    public void showResponse(int apiType, String listType,Object o) {

        if(apiType== HttpConstant.REGISTER_QUEST){//注册接口
            BaseResponse<String> baseResponse = (BaseResponse<String>) o;
            if (baseResponse.getStatus() == Constant.HTTP_OK) {
                mPresenter.getData(HttpConstant.UPLOAD_LOCATION_REGISTER,null,mPhoneNum);
            } else {
                if (!StringUtils.isEmpty(baseResponse.getMessage())) {
                    ToastUtils.showShort(RegisterActivity.this, baseResponse.getMessage());
                }
            }
        }

        else if(apiType==HttpConstant.UPLOAD_LOCATION_REGISTER){//手机经纬度注册接口
            dismissLoadingView();
            jumpToLoginPage(mPhoneNum);
        }

        else if(apiType==HttpConstant.VOICE_CODE){ //语音验证接口
            dismissLoadingView();
            BaseResponse<String> baseResponse = (BaseResponse<String>) o;
            if (baseResponse.getStatus() == Constant.HTTP_OK) {
                processCountDownView(do_acquire_voice_code, new SpannableString(getStringResource(R
                        .string.register_acquire_voice_code)));
            } else {
                if (StringUtils.isEmpty(baseResponse.getMessage())) {
                    ToastUtils.showShort(RegisterActivity.this, baseResponse.getMessage());
                }
            }
        }

        else if(apiType==HttpConstant.SMS_CODE){ //短信验证接口
            dismissLoadingView();
            BaseResponse<String> baseResponse = (BaseResponse<String>) o;
            if (baseResponse.getStatus() == Constant.HTTP_OK) {
                processCountDownView(do_acquire_verify_code, new SpannableString(getStringResource(R
                        .string.register_acquire_verity_code)));
            } else {
                if (StringUtils.isEmpty(baseResponse.getMessage())) {
                    ToastUtils.showShort(RegisterActivity.this, baseResponse.getMessage());
                }
            }
        }
    }

    @Override
    public void showError(Throwable e) {}

    //用户注册倒计时
    private class CustomerCountDownTimer extends CountDownTimer {

        private TextView textView;
        private Drawable background;
        private SpannableString endStrRes;

        public void updateTextView(TextView textView, SpannableString strSpan) {
            this.textView = textView;
            this.endStrRes = strSpan;
            background = this.textView.getBackground();

        }

        public CustomerCountDownTimer(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
        }

        @Override
        public void onTick(long millisUntilFinished) {
            if (this.textView == null) return;
            textView.setText((millisUntilFinished / 1000 + 1) + "s");
        }

        @Override
        public void onFinish() {
            if (this.textView == null) return;
            isStartCountDown = false;
            if (background != null) {
                this.textView.setBackground(background);
            }
            if (this.endStrRes != null) {
                this.textView.setText(endStrRes);
            }
            do_acquire_voice_code.setEnabled(true);
            do_acquire_verify_code.setEnabled(true);
        }
    }

    private String verifyParams(String phoneNum, String psw, String verifyCode) {
        if (StringUtils.isEmpty(phoneNum)) {
            return getStringResource(R.string.register_user_name_is_null);
        } else if (StringUtils.isEmpty(psw)) {
            return getStringResource(R.string.register_psw_is_null);
        } else if (StringUtils.isEmpty(verifyCode)) {
            return getStringResource(R.string.register_verify_code_is_null);
        } else if (!checkAgreement.isChecked()) {
            return getStringResource(R.string.register_not_agree);
        }
        return null;
    }

    /**
     * 注册成功请登录
     *
     * @param phoneNum
     */
    private void jumpToLoginPage(String phoneNum) {
        ARouter.getInstance().build(RouterMap.REGISTER_RESULT).withString(LoginActivity
                .USER_NAME, phoneNum.trim()).withInt("result_type", 1).navigation();
        finish();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (countDownTimer != null) {
            countDownTimer.cancel();
        }
    }
}
